package com.spring.lesson001.demo12.proxy1;

import org.junit.Test;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author vhans
 */
public class ProxyTest {

    @Test
    public void testEg1() throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        // 1.获取接口对应的代理类
        Class<IService> proxyClass = (Class<IService>) Proxy.getProxyClass(IService.class.getClassLoader(), new Class[]{IService.class});
        // 2.创建代理类的处理器
        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                System.out.println("我是InvocationHandler,被调用的方法是：" + method.getName());
                return null;
            }
        };
        // 3.创建一个代理实例
        IService proxyService = proxyClass.getConstructor(InvocationHandler.class).newInstance(invocationHandler);
        // 4.调用代理的方法
        proxyService.m1();
        proxyService.m2();
        proxyService.m3();
    }

    @Test
    public void testEg2() {
        // 1.创建代理类的处理器
        InvocationHandler invocationHandler = (o, method, objects) -> {
            System.out.println("我是InvocationHandler,被调用的方法是：" + method.getName());
            return null;
        };

        // 2.创建代理实例
        IService serviceProxy = (IService) Proxy.newProxyInstance(IService.class.getClassLoader(), new Class[]{IService.class}, invocationHandler);

        // 3.调用代理的方法
        serviceProxy.m1();
        serviceProxy.m2();
        serviceProxy.m3();
    }
}
